'use strict';

import React, {Component} from 'react'
import {RefreshControl, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import NavigationBar from '../../component/navigation/NavigationBar'
import ImageView from "../../component/common/ImageView";
import LatestSubjectComponent from "../../component/find/LatestSubjectComponent";
import FreeForumComponent from "../../component/find/FreeForumComponent";
import SpinnerLoading from "../../component/common/SpinnerLoading";

export default class Find extends Component {

    constructor(props) {
        super(props);
        this.state = {
            ready: false,
            refreshing: false,
            chosenSubjectData: [],
            latestSubjectData: [],
            freeForumData: [],
        };
    }

    componentDidMount() {
        this.requestDataSources();
    }


    componentWillUnmount() {
        this.timer1 && clearTimeout(this.timer1);
        this.timer2 && clearTimeout(this.timer2);
    }

    requestDataSources = () => {
        this.requestChosenSubject();
        this.requestLatestSubject();
        this.requestFreeForum();
        this.timer2 = setTimeout(() => this.setState({ready: true}), 300);
    };

    onRefresh = () => {
        this.setState({refreshing: true});
        this.requestDataSources();
        this.timer1 = setTimeout(() => {
            this.setState({refreshing: false});
        }, 1000);
    };


    //精选专题，换一批
    _onPressRandom = async () => {
        const result = await Services.post(ServicesApi.FIND_SUBJECT, {
            type: 'rand',
            subject_type: 'y',
            page: 1,
            limit: 3
        });
        // console.log('换一批返回--------------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let data = [];
            if (Array.isArray(result.data)) {
                data = result.data;
            }
            this.setState({chosenSubjectData: data});
        }
    };

    //请求获取自由论坛
    requestFreeForum = async () => {
        const result = await Services.post(ServicesApi.FREE_FORUM, {page: 1, limit: 3});
        // console.log('自由论坛返回--------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let data = [];
            if (Array.isArray(result.data)) {
                data = result.data;
            }
            this.setState({freeForumData: data})
        }
    };

    //请求获取最新专题
    requestLatestSubject = async () => {
        const result = await Services.post(ServicesApi.FIND_SUBJECT, {page: 1, limit: 3});
        // console.log('最新专题返回--------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let data = [];
            if (Array.isArray(result.data)) {
                data = result.data;
            }
            this.setState({latestSubjectData: data})
        }
    };

    //请求获取精选专题
    requestChosenSubject = async () => {
        const result = await Services.post(ServicesApi.FIND_SUBJECT, {subject_type: 'y', page: 1, limit: 3});
        // console.log('精选专题返回------------->',result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let data = [];
            if (Array.isArray(result.data)) {
                data = result.data;
            }
            this.setState({chosenSubjectData: data})
        }
    };

    _onPressMoreLatest = () => {
        // console.log('最新专题查看更多');
        RouterHelper.navigate('最新专题', 'LatestSubjects');
    };

    _onPressMoreForum = () => {
        // console.log('自由论坛查看更多');
        RouterHelper.navigate('自由论坛', 'FreeForumList');
    };

    renderTitleView = (props) => {
        const {title, subTitle, onPressSub, style} = props;
        return (
            <View style={[styles.titleView, style]}>
                <View style={styles.titleLeftView}>
                    <View style={styles.titleLine}/>
                    <Text style={styles.title}>{title}</Text>
                </View>
                <TouchableOpacity onPress={onPressSub}>
                    <Text style={styles.subTitle}>{subTitle}</Text>
                </TouchableOpacity>
            </View>
        )
    };

    _onPressToDetail = (item) => {
        // console.log('专题详情');
        RouterHelper.navigate('专题', 'SubjectDetail', {subject_id: item.subject_id});
    };

    renderChosenSubjectView = () => {
        const width = (SCREEN_WIDTH - 60) / 3;
        const height = width;
        return (
            <View style={styles.chosenView}>
                {this.state.chosenSubjectData.map((item, i) => {
                    const leftSpace = i === 0 ? 0 : 15;
                    return (
                        <TouchableOpacity
                            onPress={() => this._onPressToDetail(item)}
                            key={i}
                            style={[styles.chosenItemView, {width, marginLeft: leftSpace}]}
                        >
                            <ImageView
                                style={{width, height}}
                                resizeMode={'cover'}
                                source={item.subject_picture ? {uri: item.subject_picture} : null}
                            />
                            <Text style={styles.chosenItemText} numberOfLines={2}>{item.subject_title}</Text>
                        </TouchableOpacity>
                    )
                })}
            </View>
        )
    };

    renderLatestSubjectView = () => {
        return (
            <View>
                {this.state.latestSubjectData.map((item, i) => {
                    return (
                        <LatestSubjectComponent
                            key={i}
                            item={item}
                            index={i}
                        />
                    )
                })}
            </View>
        )
    };

    _onUpdateForumData = (item, index) => {
        // console.log(index,item);
        let temp = this.state.freeForumData.slice();
        temp[index] = item;
        this.setState({freeForumData: temp})
    };

    renderFreeForumView = () => {
        return (
            <View style={{marginBottom: 10}}>
                {this.state.freeForumData.map((item, i) => {
                    return (
                        <FreeForumComponent
                            key={i}
                            item={item}
                            index={i}
                            onPressDZ={(item, index) => this._onUpdateForumData(item, index)}
                        />
                    )
                })}
            </View>
        )
    };

    render() {
        let {refreshing, ready} = this.state;
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={'发现'}
                    renderLeftAction={null}
                />
                {ready ?
                    <ScrollView
                        style={styles.scroll}
                        refreshControl={
                            <RefreshControl
                                title='Loading...'
                                refreshing={refreshing}
                                onRefresh={this.onRefresh}
                                tintColor="#0398ff"
                                colors={['#0398ff']}
                                progressBackgroundColor="#fff"
                            />
                        }
                    >
                        <this.renderTitleView
                            title={'精选专题'}
                            subTitle={'换一批'}
                            style={{marginTop: 15}}
                            onPressSub={() => this._onPressRandom()}
                        />
                        <this.renderChosenSubjectView/>
                        <this.renderTitleView
                            title={'最新专题'}
                            subTitle={'查看更多'}
                            style={{marginTop: 15}}
                            onPressSub={() => this._onPressMoreLatest()}
                        />
                        <this.renderLatestSubjectView/>
                        <this.renderTitleView
                            title={'自由论坛'}
                            subTitle={'查看更多'}
                            style={{marginTop: 15}}
                            onPressSub={() => this._onPressMoreForum()}
                        />
                        <this.renderFreeForumView/>
                    </ScrollView>
                    : <SpinnerLoading/>}
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    scroll: {
        flex: 1,
    },
    titleView: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
    },
    titleLeftView: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    titleLine: {
        width: 8,
        height: 19,
        backgroundColor: "#ffa64f",
    },
    title: {
        fontFamily: "PingFangSC-Medium",
        fontSize: FontSize(16),
        color: "#333",
        marginLeft: 14,
    },
    subTitle: {
        fontSize: FontSize(14),
        color: "#929292",
    },
    chosenView: {
        marginHorizontal: 12,
        marginTop: 12,
        flexDirection: 'row',
        alignItems: 'center',
    },
    chosenItemView: {
        overflow: 'hidden',
        borderRadius: 7,
        alignItems: 'center',
        borderColor: "#dbdbdb",
        borderWidth: Theme.minPixel,
    },
    chosenItemText: {
        minHeight: 30,
        fontSize: 12,
        color: "#333",
        marginVertical: 5,
        textAlign: 'center',
        textAlignVertical: 'center',
        marginHorizontal: 10,
        includeFontPadding: false,
    },
});